import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_api_path.dart';
import 'package:xindong/common/xindong_define.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/manager/network/xindong_networking.dart';
import 'package:xindong/models/xindong_auth_class.dart';
import 'package:xindong/models/xindong_photo_class.dart';
import 'package:xindong/models/user/xindong_kongjian_user.dart';
import 'package:xindong/handle/xindong_user_handle.dart';
import 'package:xindong/routes/tab_moments/controller/xindong_dongtai_handle.dart';
import 'package:xindong/routes/tab_moments/model/xindong_dongtai_class.dart';
import 'package:xindong/utils/xindong_image_util.dart';
import 'package:xindong/utils/xindong_text_util.dart';
import 'package:xindong/widgets/dialog/xindong_alert_message.dart';

class XinDongKongJianCtr extends GetxController {
  static XinDongKongJianCtr get to => Get.find();
  static const updateIdLoadingInfo = "loadingInfo";
  static const updateIdLoadingMoment = "loadingMoment";
  static const updateIdLoadingAuth = "loadingAuth";
  static const updateIdLoadingVideo = "loadingVideo";
  static const updateIdLoadingPhoto = "loadingPhoto";

  // 头部高度
  final double headerHeight = screenWidth;

  // 其他属性
  final scrollController = ScrollController();
  final userHandle = XinDongUserHandle();
  final momentHandle = XinDongDongTaiHandle();

  // 导航栏透明度
  double appBarAlpha = 0.0;

  // 底部工具栏高度
  double utilBarHeight = bottomBarHeight;

  // 状态栏/导航栏
  // 默认透明
  // 默认暗色模式（黑底白字）
  bool isTransparentAppBar = true;
  Brightness brightness = Brightness.dark;

  // 用户异常
  bool isUserException = false;

  // 模型
  XinDongSpaceUser? userspace;
  List<XinDongDongTaiClass> moments = [];
  List<XinDongAuthClass> auths = [];
  List<XinDongPhotoClass> photos = []; // 跳转页面才使用，不然用photo_show就够了
  String distanceText = "保密";

  @override
  void onInit() {
    super.onInit();
    scrollController.addListener(() {
      final scrollDistance = headerHeight - kAppBarHeight - statusBarHeight;
      if (scrollController.offset > scrollDistance) {
        if (!isTransparentAppBar) {
          return;
        }
        appBarAlpha = 1.0;
        isTransparentAppBar = false;
        brightness = Brightness.light;
        update(["appBarAlpha"]);
      } else {
        if (scrollController.offset < 0) {
          appBarAlpha = 0.0;
        } else {
          appBarAlpha = scrollController.offset / scrollDistance;
        }
        if (!isTransparentAppBar) {
          isTransparentAppBar = true;
          brightness = Brightness.dark;
        }
        update(["appBarAlpha"]);
      }
    });
  }

  setup() {
    // 导航栏透明度
    appBarAlpha = 0;
    // 是我自己，就隐藏工具栏
    utilBarHeight = userspace?.isSelf == true ? bottomBarHeight : bottomBarHeight + 40 + 44;
    // 距离
    distanceText = userspace?.isSelf == true
        ? ""
        : userspace?.hide_distance == 1
            ? "保密"
            : (userspace?.city ?? "") + (userspace?.distance ?? "");
  }
}

extension Handle on XinDongKongJianCtr {
  Future<bool> requestKongJian(String userId) async {
    final data = await userHandle.userInfo(userId: userId);
    if (data != null) {
      if (data.isEmpty) {
        isUserException = true;
      } else {
        userspace = XinDongSpaceUser.fromJson(data);
        userspace?.userid = userId;
        userspace?.user_id = userId;
        setup();
      }
      update([XinDongKongJianCtr.updateIdLoadingInfo]);
    }
    return data != null && data.isNotEmpty;
  }

  void requestConfig(String userId) async {
    final model = await userHandle.userConfig(userId: userId);
    if (model != null) {
      update([XinDongKongJianCtr.updateIdLoadingVideo]);
    }
  }

  void requestUserVideoList(String userId) async {
    final data = await userHandle.userVideoList(userId: userId);
    if (data.isNotEmpty) {
      // auths = data;
      update([XinDongKongJianCtr.updateIdLoadingVideo]);
    }
  }

  void requestUserAuthList(String userId) async {
    final data = await userHandle.userAuthList(userId: userId);
    if (data.isNotEmpty) {
      auths = data;
      update([XinDongKongJianCtr.updateIdLoadingAuth]);
    }
  }

  void requestUserMoment(String userId) async {
    momentHandle.requestListWithUserId(
      userId: userId,
      yemian: 0,
      yemianSize: 1,
      callback: (object) {
        if (object.code == XinDongServerStatus.success) {
          List list = object.result;
          if (list.isNotEmpty) {
            moments = list.map((e) => XinDongDongTaiClass.fromJson(e)).toList();
            update([XinDongKongJianCtr.updateIdLoadingMoment]);
          }
        }
      },
    );
  }

  void requestUserPhotos() async {
    if (TextUtil.isEmpty(userspace?.uid)) {
      return;
    }
    final object = await XinDongNetworking.instance.request(
      XinDongApi.albumList,
      method: XinDongHttpMethod.post,
      parameters: {"to_user": userspace?.uid, "slide": 0},
    );
    if (object.code == XinDongServerStatus.success) {
      List list = object.result;
      photos = list.map((e) => XinDongPhotoClass.fromJson(e)).toList();
      update([XinDongKongJianCtr.updateIdLoadingPhoto]);
    }
  }

  // 关注
  void requestAttention() async {
    if (TextUtil.isEmpty(userspace?.uid)) {
      return;
    }
    final result = await userHandle.attention(userId: userspace?.uid);
    if (result) {
      userspace?.love = userspace?.love == 1 ? 0 : 1;
      if (userspace?.love == 1) {
        userspace?.attention = (userspace?.attention ?? 0) + 1;
      } else {
        userspace?.attention = (userspace?.attention ?? 0) - 1;
      }
      update([XinDongKongJianCtr.updateIdLoadingInfo]);
    }
  }

  // 赞
  void requestVoiceZan() async {
    if (TextUtil.isEmpty(userspace?.uid)) {
      return;
    }
    final object = await XinDongNetworking.instance.request(
      XinDongApi.voiceZan,
      method: XinDongHttpMethod.post,
      parameters: {"to_user": userspace?.uid},
    );
    if (object.code == XinDongServerStatus.success) {
      userspace?.has_voice_zan = 1;
      userspace?.voice_zan = (userspace?.voice_zan ?? 0) + 1;
      update([XinDongKongJianCtr.updateIdLoadingInfo]);
    }
  }

  // 上传
  void uploadAlbum({bool updatePhotoList = false}) async {
    if (TextUtil.isEmpty(userspace?.uid)) {
      return;
    }
    List<File>? list = await ImageUtil.selectPhotos(maxCount: 1);
    if (list == null) {
      return;
    }
    showLoading();
    final fileUrl = await XinDongNetworking.instance.uploadFile(filePath: list.first.path);
    if (TextUtil.isEmpty(fileUrl)) {
      mDebugPrint('返回图片结果$fileUrl');
      hideLoading();
      return;
    }
    final object = await XinDongNetworking.instance.request(
      XinDongApi.albumUpload,
      method: XinDongHttpMethod.post,
      parameters: {"burn": 0, "packet": 0, "types": 1, "photo_album": fileUrl},
    );
    hideLoading();
    if (object.code == XinDongServerStatus.success) {
      if (updatePhotoList) requestUserPhotos();
      requestKongJian(userspace!.uid);
    }
  }

  // 删除
  void albumDelete(XinDongPhotoClass model) async {
    if (TextUtil.isEmpty(userspace?.uid)) {
      return;
    }
    String msg = model.is_auth == 1 ? '删除后，将无法再次获得本人认证照片，是否继续？' : '是否确定删除该图？';
    XinDongAlertMessage.show(
      content: msg,
      onTapButton: () async {
        final object = await XinDongNetworking.instance.request(
          XinDongApi.albumDelete,
          method: XinDongHttpMethod.post,
          parameters: {"img_id": model.id},
        );
        hideLoading();
        if (object.code == XinDongServerStatus.success) {
          requestUserPhotos();
          requestKongJian(userspace!.uid);
        }
      },
    );
  }
}
